// 引入进度条组件
import Nprogress from "nprogress";

// 公共路径前缀
const BASE_URL = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    // 这里接收到的params参数是 对象形式
    // url是传过来的局部路径，需要拼接上公共路径前缀
    // fetch的传参是在路径后面直接拼接上 ?query (查询字符串)
    if (params) {
      url += "?";
      for (const key in params) {
        url += key + "=" + params[key] + "&";
      }
      url = url.substring(0, url.length - 1);
    }
    return new Promise((resolve) => {
      return fetch(BASE_URL + url)
        .then((response) => response.json())
        .then((res) => {
          if (res.status === 0) {
            resolve(res);
          }
        });
    });
  },
  post(url, data) {
    Nprogress.start();
    return new Promise((resolve) => {
      return fetch(BASE_URL + url, {
        method: "POST",
        headers: {
          "Content-type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => response.json())
        .then((res) => {
          if (res.status === 0) {
            Nprogress.done();
            resolve(res);
          }
        });
    });
  },
};

export default http;
